package com.android.manghe.orderpay.activity

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.base.frame.view.MVPActivity
import com.android.base.tools.DisplayUtil
import com.android.base.tools.ToastUtil
import com.android.base.view.recycler.RecyclerViewDivider
import com.android.manghe.R
import com.android.manghe.common.activity.PayFailActivity
import com.android.manghe.common.activity.PaySuccessActivity
import com.android.manghe.common.model.BuyGoodShangMengZhiFuRes
import com.android.manghe.common.model.PaymentTypeRes
import com.android.manghe.common.webview.SimpleWebViewActivity
import com.android.manghe.config.events.PaySuccessEvent
import com.android.manghe.config.events.RefreshCartEvent
import com.android.manghe.config.events.RefreshMemberInfoEvent
import com.android.manghe.coupon.adapter.PaymentAdapter
import com.android.manghe.market.model.CartGoodListRes
import com.android.manghe.mine.activity.AddressListActivity
import com.android.manghe.mine.model.AddressInfo
import com.android.manghe.orderpay.adapter.MarketPayGoodAdapter
import com.android.manghe.orderpay.presenter.PMarketOrderPayFromCart
import com.android.manghe.quickpay.activity.QuickPayDetailActivity
import com.android.manghe.view.AutoHeightLayoutManager
import com.android.manghe.view.dialog.ConfirmPayResultDialog
import com.eightbitlab.rxbus.Bus
import com.eightbitlab.rxbus.registerInBus
import kotlinx.android.synthetic.main.activity_order_pay.btnConfirmPay
import kotlinx.android.synthetic.main.activity_order_pay.etMark
import kotlinx.android.synthetic.main.activity_order_pay.ivClosePay
import kotlinx.android.synthetic.main.activity_order_pay.layoutAddAddress
import kotlinx.android.synthetic.main.activity_order_pay.layoutAddress
import kotlinx.android.synthetic.main.activity_order_pay.layoutHaveAddress
import kotlinx.android.synthetic.main.activity_order_pay.layoutPay
import kotlinx.android.synthetic.main.activity_order_pay.paymentRecyclerView
import kotlinx.android.synthetic.main.activity_order_pay.tvAddr
import kotlinx.android.synthetic.main.activity_order_pay.tvAddrName
import kotlinx.android.synthetic.main.activity_order_pay.tvAddrTel
import kotlinx.android.synthetic.main.activity_order_pay.tvPay
import kotlinx.android.synthetic.main.activity_order_pay.tvPriceSmall
import kotlinx.android.synthetic.main.activity_order_pay.tvTruePrice
import kotlinx.android.synthetic.main.activity_order_pay_from_cart.*
import java.text.DecimalFormat

class MarketOrderPayFromCartActivity : MVPActivity<PMarketOrderPayFromCart>() {

    private val ReqCode_SelectAddress = 1001
    private var mPaymentAdapter: PaymentAdapter? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_order_pay_from_cart
    }

    override fun initData(savedInstanceState: Bundle?) {
        Bus.observe<PaySuccessEvent>().subscribe {
            Bus.send(RefreshCartEvent())
            finish()
        }.registerInBus(this)

        p.selectedGoodList =
            intent.getSerializableExtra("selectedGoodList") as List<CartGoodListRes.DataBean.CartGoodsBean>

        titleBar.setToolbar("确认订单").setLeftIcon(R.mipmap.icon_back_black)
            .setTitleAndStatusBgColor(R.color.white)
//        val config = ConfigHolder.getConfigInfo(this)
//        if (config != null && config.order_exempt_rule_switch == 1) {
//            titleBar.setRightText("规则") {
//                AnalyzeUtil.clickRule(this, 2)
//                WebTextActivity.showActivity(
//                    this,
//                    "商品助力规则",
//                    ConstantsUrl.domain + ConstantsUrl.ZHULI_RULE
//                )
//            }.setRightFontColor(ContextCompat.getColor(this, R.color.colorFont99))
//        }

        // 初始化支付方式列表
        paymentRecyclerView.layoutManager =
            AutoHeightLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        mPaymentAdapter = PaymentAdapter(this, ArrayList<PaymentTypeRes.DataBean.PaymentBean>())
        mPaymentAdapter!!.hideDesc()
        paymentRecyclerView.addItemDecoration(
            RecyclerViewDivider(
                this,
                LinearLayoutManager.HORIZONTAL
            )
        )
        paymentRecyclerView.adapter = mPaymentAdapter
        mPaymentAdapter!!.setOnItemClickListener { adapter, view, position ->
            val item = adapter.data[position] as PaymentTypeRes.DataBean.PaymentBean
            mPaymentAdapter?.selectedItem(item)
            p.setPayType(item)
        }
        // 配送地址
        layoutAddress.setOnClickListener {
            //添加地址,切换地址
            open(
                AddressListActivity::class.java,
                hashMapOf<String, Any>("isToSelect" to true),
                ReqCode_SelectAddress
            )
        }
        // 结算按钮
        tvPay.setOnClickListener {
            // 显示支付方式视图
            layoutPay.visibility = View.VISIBLE
        }
        btnConfirmPay.setOnClickListener {
            if (p.currentAddress == null) {
                ToastUtil.showShort(this, "请填写配送地址")
            } else {
                layoutPay.visibility = View.GONE
                p.toPay(etMark.text.toString().trim(), 0)
            }
        }
        ivClosePay.setOnClickListener {
            layoutPay.visibility = View.GONE
        }
        layoutPay.setOnClickListener {
            layoutPay.visibility = View.GONE
        }
        p.getMemberInfo()
        p.loadAddressList()
        p.getPaymentType()
    }

    override fun onBackPressed() {
        if (layoutPay.visibility == View.VISIBLE) {
            layoutPay.visibility = View.GONE
        } else {
            super.onBackPressed()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (ReqCode_SelectAddress == requestCode) {
                p.setCurrentAddress(data?.getSerializableExtra("addressInfo") as AddressInfo)
                showAddress(p.currentAddress)
            }else if(requestCode == 1000 || requestCode == 2000){
                if(data != null && data.extras != null && data.extras.getBoolean("fail" , false)){
                    finish()
                    open(PayFailActivity::class.java)
                    Bus.send(RefreshMemberInfoEvent())
                    return
                }
                //翼支付、快捷支付 支付成功
                finish()
                open(PaySuccessActivity::class.java)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Bus.unregister(this)
    }

    fun showGoodListView(memberLevel: Int) {
        try {
            tvPay.text = "结算(${p.selectedGoodList.size})"

            val adapter = MarketPayGoodAdapter(this, p.selectedGoodList)
            goodRecyclerView.layoutManager = AutoHeightLayoutManager(this)
            goodRecyclerView.addItemDecoration(
                RecyclerViewDivider(
                    this,
                    LinearLayoutManager.HORIZONTAL,
                    3,
                    ContextCompat.getColor(this, R.color.backgroundGray)
                )
            )
            goodRecyclerView.adapter = adapter

            var allPrice = 0.0
            var totalQty = 0
            for (good in p.selectedGoodList) {
                allPrice += good.subtotal

                totalQty += good.qty
            }
            tvTotalQtyTip.text = "共${totalQty}件商品"

            if(memberLevel > 0) {
                allPrice *= when (memberLevel) {
                    1 -> {
                        0.98
                    }
                    2 -> {
                        0.97
                    }
                    3 -> {
                        0.96
                    }
                    else->{
                        0.95
                    }
                }
            }

            val format = DecimalFormat("0.00")
            val priceStr = format.format(allPrice)

            tvTruePrice.text = "￥$priceStr" //底部总计
            tvPriceSmall.text = tvTruePrice.text //小计
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun showAddress(addressInfo: AddressInfo?) {
        p.setCurrentAddress(addressInfo)
        if (addressInfo == null) {
            layoutAddAddress.visibility = View.VISIBLE
            layoutHaveAddress.visibility = View.GONE
        } else {
            layoutAddAddress.visibility = View.GONE
            layoutHaveAddress.visibility = View.VISIBLE

            tvAddrName.text = addressInfo.name
            tvAddrTel.text = addressInfo.mobile
            tvAddr.text = addressInfo.area + " " + addressInfo.address
        }
    }

    fun updatePayments(paymentList: List<PaymentTypeRes.DataBean.PaymentBean>) {

        mPaymentAdapter?.let {
            it.update(paymentList)
        }
        try {
            val lp = LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                paymentList.size * DisplayUtil.dip2px(this, 60f)
            )
            lp.topMargin = DisplayUtil.dip2px(this, 20f)
            lp.bottomMargin = DisplayUtil.dip2px(this, 20f)
            paymentRecyclerView.layoutParams = lp
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }


    fun payFail() {
        ToastUtil.showShort(this, "未完成支付")
    }

    fun paySuccess() {
        finish()
        open(PaySuccessActivity::class.java)
    }

    fun toPayByH5(url: String) {
        SimpleWebViewActivity.showActivity(this, url, "支付")
    }

    fun openQuickPay(buyGoodShangMengZhiFuData: BuyGoodShangMengZhiFuRes.DataBean){
        open(QuickPayDetailActivity::class.java, mapOf("buyGoodShangMengZhiFuData" to buyGoodShangMengZhiFuData), 2000)
    }

    fun toPayByBrowser(url: String, orderId: String) {
        val uri: Uri = Uri.parse(url)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
        //弹出让用户确定是否支付成功的弹出框
        orderId?.let {
            val dialog = ConfirmPayResultDialog(this, orderId, object : ConfirmPayResultDialog.CallBack{
                override fun callBack(orderId: String) {
                    //显示支付成功界面
                    p.checkOrderStatus(orderId)
                }
            })
            dialog.show()
        }
    }
}